package com.cictec.middleware.tde.rm.disp.receiver.handler;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Result;
import com.cictec.middleware.commons.utils.ResultUtil;
import com.cictec.middleware.core.entity.Device;
import com.cictec.middleware.feign.distribute.MiddlewareDeviceFileUploadService;
import com.cictec.middleware.feign.distribute.MiddlewareDeviceService;
import com.cictec.middleware.tde.rm.SessionManager;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x01TerminalMessage;

/**
 * 连接请求处理，需要应答【已在AutoResponseFilter中配置回复应答】
 * 
 * @author Administrator
 *
 */
@Component
@HandleMessages(0x01)
public class TerminalConnectRequestHandler extends AbstractReceiverHandler {

	private static Logger logger = LoggerFactory.getLogger(TerminalConnectRequestHandler.class);

	@Autowired
	private SessionManager sessionManager;
	@Autowired
	private MiddlewareDeviceFileUploadService middlewareDeviceFileUploadService;
	@Autowired
	private MiddlewareDeviceService middlewareDeviceService;

	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {

		Rm0x01TerminalMessage msg = (Rm0x01TerminalMessage) message;
		logger.debug("【0x01  连接请求】Session {} 终端ID： {} 设备编号： {} 序列号：{} SIM卡 {} 掉线原因： {} 重连次数： {}",
				message.getSessionId(), msg.getTerminalId(), msg.getTerminalId(), msg.getSerialNumber(), msg.getSim(),
				msg.getLastCloseReason(), msg.getNetConnectTimes());
		
		String serialNumber = msg.getSerialNumber();
		String terminalId = msg.getTerminalId();

		Device device = middlewareDeviceService.getDeviceBySerialNumber(serialNumber);
		if(device == null){
			device = middlewareDeviceService.getDeviceByDevCode(terminalId);
		}
		
		if(device != null || sessionManager.isAuthenticated(session)){
			Result result = middlewareDeviceService.deviceConnectByDevcode(terminalId);

			// 如果认证通过 通过设备号注册设备
			if(ResultUtil.isSuccess(result)){
				
				judgeUpdateSerialNumber(device, msg);	// 判定是否更新设备序列号
				
				sessionManager.tmpToRegistered(msg.getSessionId(), terminalId);
				/* **** 设置位置数据上传的时间间隔  start ***/
				sendMessageToTerminal(createUploadInterval(msg), session);
				/* **** 设置位置数据上传的时间间隔  end   ***/
			}else{
				logger.debug("【0x01  连接请求】Session {} 终端 {} 找不到序列号{} 对应设备编号  busInstance为null，关闭session", msg.getSessionId(), terminalId, serialNumber);
				sessionManager.closeSession(session);
			}
		}else{
			sessionManager.closeSession(session);
			logger.warn("【0x01  连接请求】Session {} 终端ID： {} 序列号：{} 找不到对应序列号对应的设备", message.getSessionId(), msg.getTerminalId(), msg.getSerialNumber());
		}
	}
	
	private void judgeUpdateSerialNumber(Device device, Rm0x01TerminalMessage msg){
		String serialNumber = msg.getSerialNumber();
		String terminalId = msg.getTerminalId();
		
		if(device.getDevRefId() == null || !serialNumber.equals(device.getDevRefId())){
			logger.debug("【0x01  连接请求】Session {} 终端 {} 序列号 {} 与服务器设置不一致 {}，更新服务器设备序列号", msg.getSessionId(), terminalId, serialNumber, device.getDevRefId());
			middlewareDeviceService.updateDeviceSerialNumber(terminalId, serialNumber);
		}
	}

}
